import config from '@/config'
import axios from 'axios'
import Crypto from '@/utils/crypto/crypto'
//import moment from 'moment'

var Buffer = require('buffer').Buffer;

export function getUploadInfo(param) {
    const url = config.serverURI + config.api.getUploadInfo
    return axios({
        method: 'post',
        url: url,
        data: param
    })
}

export function uploadFileToOss(file, fileBackInfo) {
    let nowString = moment().utc().format("ddd, DD MMM YYYY HH:mm:ss") + ' GMT'
    let fileName = fileBackInfo.upload_name
    let message = [
        "PUT",
        "",
        file.type,
        nowString,
        `x-oss-date:${nowString}`,
        `x-oss-security-token:${fileBackInfo.sts_token.ecurity_token}`,
        // "x-oss-user-agent:aliyun-sdk-js/4.4.4 Chrome 70.0.3538.110 32-bit on Windows Server 2008 R2 / 7 64-bit",
        `/${fileBackInfo.bucket}/${fileName}`]

    let signature = Crypto.createHmac('sha1', fileBackInfo.sts_token.access_key_secret).update(new Buffer(message.join('\n'), 'utf8')).digest('base64')

    const url = fileBackInfo.bucket.toLowerCase() === 'funkey-private' ? config.ossPrivateURI + '/' + fileName : config.ossPublicURI + '/' + fileName
    //
    // let param = new FormData()
    // param.append('file', file, fileName) //通过append向form对象添加数据

    let param = new Blob([file])

    return new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            type: 'PUT',
            processData:false,
            headers: {
                'authorization': 'OSS ' + fileBackInfo.sts_token.access_key_id + ':' + signature,
                'x-oss-date': nowString,
                'x-oss-security-token': fileBackInfo.sts_token.ecurity_token,
                // "x-oss-user-agent": "aliyun-sdk-js/4.4.4 Chrome 70.0.3538.110 32-bit on Windows Server 2008 R2 / 7 64-bit",
                "Content-Type": file.type,
            },
            data: param,
            success: function () {
                resolve({})
            },
            error: function () {
                reject({})
            }
        })
    })
}

export function notifyFileUploadComplete(param) {
    const url = config.serverURI + config.api.notifyFileUploadComplete

    return axios({
        method: 'post',
        url: url,
        data: param
    })
}
